<!doctype html>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css"
      integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.2.1.min.js" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js"
        integrity="sha384-b/U6ypiBEHpOf/4+1nzFpr53nxSS+GLCkfwBdFNTxtclqqenISfwAzpKaMNFNmj4"
        crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js"
        integrity="sha384-h0AbiXch4ZDo7tp9hKZ4TsHbi047NrKGLO3SEJAg45jXxnGIfYzk4Si90RDIqNm1"
        crossorigin="anonymous"></script>
<script src="/socket.io/socket.io.js"></script>
<div class="container">
    <br>
    <div class="jumbotron">
        <h1>Send Message</h1>
        <br>
        <input id="name" class="form-control" placeholder="Name">
        <br>
        <textarea id="message" class="form-control" placeholder="Message"></textarea>
        <br>
        <button id="send" class="btn btn-success">Send</button>
    </div>
    <div id="messages">

    </div>
</div>

<script>

    var socket = io();
    $(() => {
        //绑定了id的button按钮，点击时候触发的script函数指向 addMessage()
        $("#send").click(() => {
            var newMessage = {
                name: $("#name").val(),
                message: $("#message").val()
            };
            postMessage(newMessage);
        });

        getMessage();
    });

    socket.on('message', addMessage);

    function addMessage(message) {
        $("#messages").append(`<h4> ${message.name} </h4> <p> ${message.message} </p>`);
    }

    function getMessage() {
        $.get('http://127.0.0.1:8989/messages', (data) => {
            data.forEach(addMessage);
        })
    }

    function postMessage(message) {
        $.post('http://127.0.0.1:8989/messages', message);
    }
</script>